package controllers

import (
	"github.com/astaxie/beego/orm"
	"github.com/gogf/gf/os/glog"
	"mdblog/models"
	"mdblog/models/blog"
)

type BlogAdminController struct {
	BaseController
}

func (o *BlogAdminController) Prepare() {
	if o.Ctx.Request.RequestURI != AdminLoginPath {
		if u := o.GetSession("user"); u == nil {
			o.Redirect(AdminLoginPath, 302)
		} else {
			o.Data["User"] = u
		}
	}
	o.Data["Configs"], _ = models.GetAllConfigs()
}

func (o *BlogAdminController) ArticleCreate() {
	classify, _ := blog.GetAllBlogClassify()
	o.Data["Classify"] = classify
	o.TplName = "blog/admin/article/create.html"
}

func (o *BlogAdminController) ArticleEdit() {
	id, _ := o.GetInt(":id")
	article, err := blog.GetBlogArticle(id)
	if err != nil {
		glog.Errorf("Get article err:%s", err.Error())
		o.Abort("404")
	}

	classify, _ := blog.GetAllBlogClassify()
	o.Data["Classify"] = classify
	o.Data["Article"] = article
	o.TplName = "blog/admin/article/edit.html"
}

func (o *BlogAdminController) ArticleList() {
	classify, _ := blog.GetAllBlogClassify()
	o.Data["Classify"] = classify
	o.TplName = "blog/admin/article/list.html"
}

func (o *BlogAdminController) ClassifyList() {
	o.TplName = "blog/admin/classify/list.html"
}

func (o *BlogAdminController) ClassifyAdd() {
	o.TplName = "blog/admin/classify/create.html"
}

func (o *BlogAdminController) ResourceList() {
	o.TplName = "blog/admin/resources/list.html"
}

func (o *BlogAdminController) ArticleTargets() {
	o.TplName = "blog/admin/targets/list.html"
}

func (o *BlogAdminController) ArticleTargetCreate() {
	classify, _ := blog.GetAllBlogClassify()
	o.Data["Classify"] = classify
	o.TplName = "blog/admin/targets/create.html"
}

func (o *BlogAdminController) SiteConfigList() {
	o.Data["Configs"], _ = models.GetAllConfigs()
	o.TplName = "blog/admin/config/list.html"
}

func (o *BlogAdminController) SiteConfigCreate() {
	o.TplName = "blog/admin/config/create.html"
}

func (o *BlogAdminController) SiteConfigEdit() {
	if id, _ := o.GetInt(":id"); id == 0 {
		o.Abort("404")
	} else {
		config, err := models.GetConfigFromId(id)
		if err != nil {
			o.Abort("500")
		} else {
			o.Data["Config"] = config
			o.TplName = "blog/admin/config/edit.html"
		}
	}
}

func (o *BlogAdminController) NoticeList() {
	o.TplName = "blog/admin/notice/list.html"
}

func (o *BlogAdminController) NoticeCreate() {
	o.TplName = "blog/admin/notice/create.html"
}

func (o *BlogAdminController) NoticeEdit() {
	id, _ := o.GetInt(":id")
	if id == 0 {
		o.Abort("500")
	}
	notice, err := blog.GetNoticeFromId(id)
	if err != nil {
		if err == orm.ErrNoRows {
			o.Abort("404")
		} else {
			o.Abort("500")
		}
	}
	o.Data["Notice"] = notice
	o.TplName = "blog/admin/notice/edit.html"
}

func (o *BlogAdminController) CarouselList() {
	o.TplName = "blog/admin/carousel/list.html"
}

func (o *BlogAdminController) CarouselCreate() {
	o.TplName = "blog/admin/carousel/create.html"
}
